package com.unittec.drainage.provider.auth.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.unittec.drainage.sdk.auth.request.Req101209;
import com.unittec.drainage.sdk.auth.response.Res101209;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.unittec.drainage.provider.auth.entity.SysRole;
import com.unittec.drainage.provider.auth.entity.SysRolePermission;
import com.unittec.drainage.provider.auth.service.SysRolePermissionService;
import com.unittec.drainage.provider.auth.service.SysRoleService;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.provider.utils.ValidationUtils;
import com.unittec.drainage.sdk.auth.request.Req101201;
import com.unittec.drainage.sdk.auth.request.Req101202;
import com.unittec.drainage.sdk.auth.request.Req101203;
import com.unittec.drainage.sdk.auth.request.Req101204;
import com.unittec.drainage.sdk.auth.request.Req101205;
import com.unittec.drainage.sdk.auth.request.Req101206;
import com.unittec.drainage.sdk.auth.request.Req101207;
import com.unittec.drainage.sdk.auth.request.Req101208;
import com.unittec.drainage.sdk.auth.response.Res101201;
import com.unittec.drainage.sdk.auth.response.Res101202;
import com.unittec.drainage.sdk.auth.response.Res101203;
import com.unittec.drainage.sdk.auth.response.Res101204;
import com.unittec.drainage.sdk.auth.response.Res101205;
import com.unittec.drainage.sdk.auth.response.Res101206;
import com.unittec.drainage.sdk.auth.response.Res101207;
import com.unittec.drainage.sdk.auth.response.Res101208;
import com.unittec.drainage.sdk.log.enums.LogOperateEnum;
import com.unittec.drainage.sdk.log.enums.LogStatusEnum;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.root.enums.BizCode;
import com.unittec.drainage.sdk.root.enums.BizCodeEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author chengjie
 * @description 角色管理
 * @date 2019/10/18
 */
@RestController
@Api(tags = "角色管理")
public class SysRoleController {

    @Autowired
    Log log;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysRolePermissionService sysRolePermissionService;

    @RequestMapping(value = "/101201", method = RequestMethod.POST)
    @ApiOperation(value = "角色分页列表", notes = "角色分页列表")
    @ResponseBody
    public Result<Res101201> getRolePage(@RequestBody GatewayRequest<Req101201> req) {
        log.debug(req, "getRolePage {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101201 res101201 = null;
        try {
            IPage<Map<String, Object>> pageList = sysRoleService.selectSysRolePage(req.getContent());
            res101201 = new Res101201();
            res101201.setPage(pageList);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "getRolePage {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101201);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101202", method = RequestMethod.POST)
    @ApiOperation(value = "添加角色", notes = "添加角色")
    @ResponseBody
    public Result<Res101202> addSysRole(@RequestBody GatewayRequest<Req101202> req) {
        log.debug(req, "addSysRole {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101202 res101202 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysRole sysRole = new SysRole();
            BeanUtils.copyProperties(req.getContent(), sysRole);
            boolean ok = sysRoleService.save(sysRole);
            if (ok) {
                res101202 = new Res101202();
                res101202.setIsSuccess(true);
                bizCodeEnum = BizCode.SUCCESS;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101202", JSON.toJSONString(req), "添加角色", log.buildErrmsg(e),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "addSysRole {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101202", JSON.toJSONString(req), "添加角色", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101202);
        } else {
            log.addOperateLog("101202", JSON.toJSONString(req), "添加角色", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101203", method = RequestMethod.POST)
    @ApiOperation(value = "修改角色", notes = "修改角色")
    @ResponseBody
    public Result<Res101203> updateSysRole(@RequestBody GatewayRequest<Req101203> req) {
        log.debug(req, "updateSysRole {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101203 res101203 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysRole sysRole = sysRoleService.getById(req.getContent().getId());
            if (sysRole != null) {
                BeanUtils.copyProperties(req.getContent(), sysRole);
                boolean ok = sysRoleService.updateById(sysRole);
                if (ok) {
                    res101203 = new Res101203();
                    res101203.setIsSuccess(true);
                    bizCodeEnum = BizCode.SUCCESS;
                }
            } else {
                bizCodeEnum = BizCode.NOT_ROLE;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101203", JSON.toJSONString(req), "修改角色", log.buildErrmsg(e),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "updateSysRole {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101203", JSON.toJSONString(req), "修改角色", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101203);
        } else {
            log.addOperateLog("101203", JSON.toJSONString(req), "修改角色", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101204", method = RequestMethod.POST)
    @ApiOperation(value = "批量删除角色", notes = "批量删除角色")
    @ResponseBody
    public Result<Res101204> deleteBatch(@RequestBody GatewayRequest<Req101204> req) {
        log.debug(req, "deleteBatch {}  ", "end");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101204 res101204 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            sysRoleService.deleteSysRole(Arrays.asList(req.getContent().getIds().split(",")));
            res101204 = new Res101204();
            res101204.setIsSuccess(true);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101204", JSON.toJSONString(req), "批量删除角色", log.buildErrmsg(e),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "deleteBatch {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101204", JSON.toJSONString(req), "批量删除角色", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101204);
        } else {
            log.addOperateLog("101204", JSON.toJSONString(req), "批量删除角色", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101205", method = RequestMethod.POST)
    @ApiOperation(value = "校验角色编码唯一", notes = "校验角色编码唯一")
    @ResponseBody
    public Result<Res101205> checkRoleCode(@RequestBody GatewayRequest<Req101205> req) {
        log.debug(req, "checkRoleCode {}  ", "end");
        BizCodeEnum bizCodeEnum = BizCode.SUCCESS;
        Res101205 res101205 = new Res101205();
        res101205.setIsSuccess(true);
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String id = req.getContent().getId();
            SysRole role = null;
            if (StringUtils.isNotEmpty(id)) {
                role = sysRoleService.getById(id);
            }
            SysRole newRole = sysRoleService
                .getOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getRoleCode, req.getContent().getRoleCode()));
            if (newRole != null) {
                if (role == null) {
                    // role为空=>新增模式=>只要roleCode存在则返回false
                    res101205.setIsSuccess(false);
                    res101205.setMessage("角色编码已存在");
                } else if (!id.equals(newRole.getId())) {
                    // 否则=>编辑模式=>判断两者ID是否一致
                    res101205.setIsSuccess(false);
                    res101205.setMessage("角色编码已存在");
                }
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "checkRoleCode {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101205);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101206", method = RequestMethod.POST)
    @ApiOperation(value = "查询角色授权", notes = "查询角色授权")
    @ResponseBody
    public Result<Res101206> queryRolePermission(@RequestBody GatewayRequest<Req101206> req) {
        log.debug(req, "queryRolePermission {}  ", "end");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101206 res101206 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String roleId = req.getContent().getRoleId();
            List<SysRolePermission> list = sysRolePermissionService
                .list(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId));
            res101206 = new Res101206();
            res101206
                .setList(list.stream().map(sysRolePermission -> String.valueOf(sysRolePermission.getPermissionId()))
                    .collect(Collectors.toList()));
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "queryRolePermission {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101206);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101207", method = RequestMethod.POST)
    @ApiOperation(value = "角色权限设置", notes = "角色权限设置")
    @ResponseBody
    public Result<Res101207> saveRolePermission(@RequestBody GatewayRequest<Req101207> req) {
        log.debug(req, "saveRolePermission {}  ", "end");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101207 res101206 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String roleId = req.getContent().getRoleId();
            String permissionIds = req.getContent().getPermissionIds();
            sysRolePermissionService.saveRolePermission(roleId, permissionIds);
            res101206 = new Res101207();
            res101206.setIsSuccess(true);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101207", JSON.toJSONString(req), "角色权限设置", log.buildErrmsg(e),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "saveRolePermission {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101207", JSON.toJSONString(req), "角色权限设置", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101206);
        } else {
            log.addOperateLog("101207", JSON.toJSONString(req), "角色权限设置", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101208", method = RequestMethod.POST)
    @ApiOperation(value = "角色列表", notes = "角色列表")
    @ResponseBody
    public Result<Res101208> getRoleList(@RequestBody GatewayRequest<Req101208> req) {
        log.debug(req, "getRoleList {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101208 res101208 = null;
        try {
            List<Map<String, Object>> list = sysRoleService.selectSysRoleList(req.getContent());
            res101208 = new Res101208();
            res101208.setList(list);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "getRoleList {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101208);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101209", method = RequestMethod.POST)
    @ApiOperation(value = "根据角色id查询角色列表", notes = "根据角色id查询角色列表")
    @ResponseBody
    public Result<Res101209> getRoleListByIds(@RequestBody GatewayRequest<Req101209> req) {
        log.debug(req, "getRoleList {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101209 res101209 = null;
        try {
            List<Map<String, Object>> list = sysRoleService.getRoleListByIds(req.getContent());
            res101209 = new Res101209();
            res101209.setList(list);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "getRoleList {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101209);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }
}
